#include<bits/stdc++.h>
using namespace std;
const int N=302;

const int dr[4]={-1,0,1,0};
const int dc[4]={0,1,0,-1};
int n,m;
char arr[N][N];
int door[26][2][2];

int main()
{
	cin>>n>>m;
	string s;
	int r0,c0,r1,c1;
	int rf,cf;
	queue<int> que;
	bool visit[N][N];
	memset(door,0,sizeof(door));
	memset(visit,false,sizeof(visit));
	
	for(int i=1;i<=n;i++)
	{
		cin>>s;
		for(int j=1;j<=m;j++)
		{
			arr[i][j]=s[j-1];
			if(arr[i][j]=='@')
			{
				que.push(i);
				que.push(j);
				visit[i][j]=true;
			}
			else if(arr[i][j]>='A'&&arr[i][j]<='Z')
			{
				char c=arr[i][j];
				if( door[c-'A'][0][0]==0)
				{
					door[c-'A'][0][0]=i;
					door[c-'A'][0][1]=j;
				}
				else
				{
					door[c-'A'][1][0]=i;
					door[c-'A'][1][1]=j;					
				}
			}
		}
	}
	
	int step=1;
	while(!que.empty())
	{
		int size=que.size()/2;
		for(int i=0;i<size;i++)
		{
			r0=que.front();
			que.pop();
			c0=que.front();
			que.pop();
			for(int j=0;j<4;j++)
			{
				r1=r0+dr[j];
				c1=c0+dc[j];
				if(r1<=0||r1>n||c1<=0||c1>m) continue;
				if(visit[r1][c1]||arr[r1][c1]=='#') continue;
				if(arr[r1][c1]=='=')
				{
					cout<<step;
					return 0;
				}
				else if(arr[r1][c1]=='.')
				{
					que.push(r1);
					que.push(c1);
					visit[r1][c1]=true;	
				}
				else if(arr[r1][c1]>='A'&&arr[r1][c1]<='Z')
				{
					visit[r1][c1]=true;	
					char c=arr[r1][c1];
					if(r1==door[ c-'A' ][0][0]
					&&c1==door[ c-'A' ][0][1])
					{
						r1=door[c-'A'][1][0];
						c1=door[c-'A'][1][1];	
					}
					else
					{
						r1=door[c-'A'][0][0];
						c1=door[c-'A'][0][1];				
					}
					que.push(r1);
					que.push(c1);
				}
			}
		}
		step++;
	}
	return 0;
}
